package com.nulldev.util.internal.backport.httpclient_rw.impl.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.nulldev.util.internal.backport.httpclient_rw.HttpHeaders;

/** A mutable builder for collecting and building HTTP headers. */
public class HttpHeadersBuilder {

	private final TreeMap<String, List<String>> headersMap;

	public HttpHeadersBuilder() {
		headersMap = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
	}

	public HttpHeadersBuilder structuralCopy() {
		HttpHeadersBuilder builder = new HttpHeadersBuilder();
		for (Map.Entry<String, List<String>> entry : headersMap.entrySet()) {
			final List<String> valuesCopy = new ArrayList<String>(entry.getValue());
			builder.headersMap.put(entry.getKey(), valuesCopy);
		}
		return builder;
	}

	public void addHeader(String name, String value) {
		headersMap.computeIfAbsent(name, k -> new ArrayList<>(1)).add(value);
	}

	public void setHeader(String name, String value) {
		// headers typically have one value
		final List<String> values = new ArrayList<String>(1);
		values.add(value);
		headersMap.put(name, values);
	}

	public void clear() {
		headersMap.clear();
	}

	public Map<String, List<String>> map() {
		return headersMap;
	}

	public HttpHeaders build() {
		return HttpHeaders.of(headersMap, Utils.ACCEPT_ALL);
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(super.toString()).append(" { ");
		sb.append(map());
		sb.append(" }");
		return sb.toString();
	}
}